<template>
  <div class="pagination">
    <button @click="handleSendPageNo(pageNo - 1)" :disabled="pageNo === 1">上一页</button>
    <button v-show="startAndEnd.start > 1" @click="handleSendPageNo(1)">1</button>
    <span v-show="startAndEnd.start > 2">...</span>
    <button v-for="(_,index) in (startAndEnd.end - startAndEnd.start + 1)" :key="_" :class="{active : (index + startAndEnd.start) == pageNo}" @click="handleSendPageNo((index + startAndEnd.start))">{{index + startAndEnd.start}}</button>
    <button v-show="startAndEnd.end < totalPage - 1">···</button>
    <button v-show="startAndEnd.end < totalPage" @click="handleSendPageNo(totalPage)">总页数：{{totalPage}}</button>
    <button @click="handleSendPageNo(pageNo + 1)" :disabled="pageNo === totalPage">下一页</button>

    <span>共 {{total}} 条</span>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props:["total","pageNo","pageSize","continues"],
  computed:{
      //1.计算总页数totalPage
      totalPage(){
          return Math.ceil(this.total/this.pageSize)
      },
      //2.计算起始和结束页
      startAndEnd(){
          const { pageNo , continues , totalPage} = this
          let start , end 
            start = pageNo - parseInt(continues/2)
            end = pageNo + parseInt(continues/2)
          if(continues > totalPage){
              start = 1,
              end = totalPage
          }else if( start < 1){
              start = 1
              end = continues
          }else if( end > totalPage ){
              start = totalPage - continues + 1
              end = totalPage
          }else{
              start = pageNo - parseInt(continues/2)
              end = pageNo + parseInt(continues/2)
          };
          return { start , end }
      }
  },
  methods:{
      handleSendPageNo(currentPageNo){
          currentPageNo = +currentPageNo // 确保传过去的是number形式的数据
          this.$emit('getPageNo',currentPageNo)
      }
  }
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #C81623;
      color: #fff;
    }
  }
  span{
    display: inline-block;
    line-height: 28px;
    font-size: 14px;
    color:gray;
    vertical-align: middle;
  }
}
</style>